package com.mysite.dubbox.test;

import com.mysite.dubbox.vo.UserVo;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

public class ConsumerRest {
    public static void main(String[] args) {

        //registerUser("http://localhost:8888/services/user/register.json", MediaType.APPLICATION_JSON_TYPE);

        //registerUser("http://localhost:8888/services/user/register.xml", MediaType.TEXT_XML_TYPE);

        //getUser("http://localhost:8888/services/user/1.json");

        //getUser("http://localhost:8888/services/user/2.xml");

        testUser();
    }

    private static void registerUser(String url, MediaType mediaType) {
        System.out.println("request url is: " + url);
        UserVo user = new UserVo(10L, "JerryLoveTom");
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(url);
        Response response = target.request().post(Entity.entity(user, mediaType));
        if (response.getStatus() == 200) {
            System.err.println("result content is: " + response.readEntity(String.class));
        }else {
            System.err.println("error code is: " + response.getStatus());
        }
        response.close();
        client.close();
    }

    private static void getUser(String url) {
        System.out.println("request url is: " + url);
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(url);
        Response response = target.request().get();
        if (response.getStatus() == 200) {
            System.err.println("result content is: " + response.readEntity(String.class));
        }else {
            System.err.println("error code is: " + response.getStatus());
        }
        response.close();
        client.close();
    }

    private static void testUser() {

        Client client = ClientBuilder.newClient();

        WebTarget target = client.target("http://localhost:8888/services/user/1.json");
        Response response = target.request().get();
        if (response.getStatus() == 200) {
            System.err.println("result content is: " + response.readEntity(String.class));
        }else {
            System.err.println("error code is: " + response.getStatus());
        }
        response.close();

        WebTarget target2 = client.target("http://localhost:8888/services/user/register.json");
        Response response2 = target2.request().post(Entity.entity(new UserVo(101L, "Jerry"), MediaType.APPLICATION_JSON_TYPE));
        if (response2.getStatus() == 200) {
            System.err.println("result content is: " + response2.readEntity(String.class));
        }else {
            System.err.println("error code is: " + response2.getStatus());
        }
        response2.close();

        client.close(); // 在真正开发中不要每次关闭client，比如HTTP长连接是由client持有的
    }
}
